package com.qcu.service.impl;

import com.qcu.service.MinioService;
import com.qcu.util.Md5Util;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * @Name: MyComputer
 * @ClassName MinioServerImpl
 * @Description:
 * @date 2025/2/15 10:53
 */
@Service
public class MinioServerImpl implements MinioService {
    @Resource
    MinioClient minioClient;
    @Value("${minio.bucket.images}")
    private String bucketName;

    @Override
    public String upload(String fileName, byte[] bytes,String type) {
        String md5Name = null;
        try {
            md5Name = Md5Util.getMD5String(fileName);
            md5Name = md5Name + "." + type;
            ByteArrayInputStream bAIS = new ByteArrayInputStream(bytes);
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(md5Name)
                            .stream(bAIS, bytes.length, -1)
                            .contentType("image/" + type)
                            .build()
            );
        }catch (Exception e){
            throw new RuntimeException("上传失败");
        }
        md5Name = "http://localhost:9000/" + bucketName + "/" + md5Name;
        return md5Name;
    }
}
